package com.tsingteng.cosfun.widget.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.bean.VideoSectionBean;
import com.tsingteng.cosfun.helper.CarouselLayoutManager;
import com.tsingteng.cosfun.helper.CenterSnapHelper;
import com.tsingteng.cosfun.helper.VideoHelper;
import com.tsingteng.cosfun.helper.ViewPagerLayoutManager;
import com.tsingteng.cosfun.ui.costar.BeforeFilmActivity;
import com.tsingteng.cosfun.utils.AppUtils;
import com.tsingteng.cosfun.utils.Command;
import com.tsingteng.cosfun.utils.DensityUtil;
import com.tsingteng.cosfun.utils.DesityUtils;
import com.tsingteng.cosfun.utils.LogUtils;
import com.tsingteng.cosfun.utils.LogonUtils;
import com.tsingteng.cosfun.utils.VideoAddCommand;
import com.tsingteng.cosfun.utils.VideoDeleteCommand;
import com.tsingteng.cosfun.utils.VideoUtils;
import com.tsingteng.cosfun.widget.PressImageView;
import com.tsingteng.cosfun.widget.dialog.adapter.VideoSliceSelectAdapter;
import com.tsingteng.cosfun.widget.dialog.adapter.VideoSliceTextAdapter;
import com.tsingteng.cosfun.widget.dialog.adapter.VideoSliceTimeAdapter;

import java.util.ArrayList;

/**
 * 描述: 选择页面
 * 创建人: 肖利
 * 时间: 2018/8/3
 * qq: (872179966)
 */

public class VideoSliceSelectDialog extends BaseDialog implements View.OnClickListener {
    private static final String TAG = "VideoSliceSelectDialog";
    private Activity context;
    private Dialog dialog;
    private PressImageView mIvAddVideo;
    private PressImageView mIvDelVideo;
    private TextView mTvShootNum;
    private VideoOrderDialog orderVideoDialog;
    private int type = 1;//1 拍摄页面进来   2  预览界面进来
    private OnDialogDissMissListener onDialogDissMissListener;
    private RecyclerView recyclerView;
    private CarouselLayoutManager viewPagerLayoutManager;
    private VideoSliceSelectAdapter videoSliceSelectAdapter;
    private CenterSnapHelper centerSnapHelper;
    private int currentPosition;
    private PressImageView mIvNext;
    private PressImageView mIvRecover;
    private RecyclerView rvLine;
    private RecyclerView rvText;
    private LinearLayoutManager linearLayoutManager;
    private VideoSliceTimeAdapter videoSliceTimeAdapter;
    private VideoSliceTextAdapter videoSliceTextAdapter;
    private LinearLayoutManager linearTextLayoutManager;

    public VideoSliceSelectDialog(Activity context, int type) {
        this.context = context;
        this.type = type;
        initView();
    }

    private void initView() {
        dialog = new Dialog(context, R.style.dialog);
        dialog.setContentView(R.layout.dialog_video_slice_select);
        recyclerView = dialog.findViewById(R.id.recycler);
        rvLine = dialog.findViewById(R.id.rv_line);
        rvText = dialog.findViewById(R.id.rv_text);
        mTvShootNum = dialog.findViewById(R.id.tv_can_shoot_num);
        mIvAddVideo = dialog.findViewById(R.id.iv_add_video);
        mIvDelVideo = dialog.findViewById(R.id.iv_delete_video);
        mIvNext = dialog.findViewById(R.id.iv_next);
        mIvRecover = dialog.findViewById(R.id.iv_recover);
        mIvAddVideo.setOnClickListener(this);
        mIvDelVideo.setOnClickListener(this);
        mIvRecover.setOnClickListener(this);
        mIvNext.setOnClickListener(this);
        dialog.findViewById(R.id.iv_order).setOnClickListener(this);
        dialog.findViewById(R.id.iv_close).setOnClickListener(this);
        //初始化adapter
        mTvShootNum.setText("选择片段(" + VideoHelper.getIntence().getVideoInfoSize() + ")");
        videoSliceTimeAdapter = new VideoSliceTimeAdapter();
        videoSliceTextAdapter = new VideoSliceTextAdapter();
        videoSliceSelectAdapter = new VideoSliceSelectAdapter();
        linearLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
        linearTextLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
        rvLine.setLayoutManager(linearLayoutManager);
        rvText.setLayoutManager(linearTextLayoutManager);
        rvLine.setAdapter(videoSliceTimeAdapter);
        rvText.setAdapter(videoSliceTextAdapter);
        viewPagerLayoutManager = new CarouselLayoutManager(context, DensityUtil.dip2px(context,100));
        recyclerView.setLayoutManager(viewPagerLayoutManager);
        viewPagerLayoutManager.setMaxVisibleItemCount(3);
        viewPagerLayoutManager.setMoveSpeed(0.7f);
        viewPagerLayoutManager.setMinScale(0.7f);
        viewPagerLayoutManager.setItemSpace(180);
        centerSnapHelper = new CenterSnapHelper();
        centerSnapHelper.attachToRecyclerView(recyclerView);
        recyclerView.setAdapter(videoSliceSelectAdapter);
        dialog.setOnDismissListener(dialog -> {
            if (onDialogDissMissListener != null) {
                onDialogDissMissListener.onDissMiss();
                currentPosition=viewPagerLayoutManager.getCurrentPosition();
                int currentPosition = viewPagerLayoutManager.getCurrentPosition();
                if ( VideoHelper.getIntence().getVideoSectionBeanList().size()>0 && currentPosition <VideoHelper.getIntence().getVideoSectionBeanList().size()) {
                    VideoHelper.getIntence().getVideoSectionBeanList().get(viewPagerLayoutManager.getCurrentPosition()).setSelect(false);
                }
            }
        });
        viewPagerLayoutManager.setOnPageChangeListener(new ViewPagerLayoutManager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                VideoHelper.getIntence().getVideoSectionBeanList().get(position).setSelect(true);
                if (currentPosition != position) {
                    VideoHelper.getIntence().getVideoSectionBeanList().get(currentPosition).setSelect(false);
                    currentPosition = position;
                    videoSliceTimeAdapter.setNewData(VideoHelper.getIntence().getVideoSectionBeanList());
                    videoSliceTextAdapter.setNewData(VideoHelper.getIntence().getVideoSectionBeanList());
                }


            }

            @Override
            public void onPageScrollStateChanged(int state) {
                LogUtils.e(TAG, state + "onPageScrollStateChanged");
            }
        });
        videoSliceSelectAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //只要点击了,就重置翻拍的标志
                VideoHelper.getIntence().setFanPai(false);
                VideoSectionBean videoSectionBean = (VideoSectionBean) adapter.getData().get(position);
                currentPosition = viewPagerLayoutManager.getCurrentPosition();
                //如果当前点击的position不是当前显示最前面的currentPosition的话
                if (currentPosition != position) {
                    currentPosition = position;
                    viewPagerLayoutManager.scrollToPosition(currentPosition);
                }
                VideoHelper.getIntence().setCurrentVideoPosition(currentPosition);
                VideoHelper.getIntence().setViewPosition(currentPosition);
                if (type == 2) {//说明是从预览的页面进来的,把原先的预览界面关掉
                    context.finish();
                }
                if (!TextUtils.isEmpty(videoSectionBean.getLocalUrl())) {
                    Intent intent = new Intent(context, BeforeFilmActivity.class);
                    intent.putExtra(VideoHelper.VIDEO_PATH, videoSectionBean.getLocalUrl());
                    context.startActivityForResult(intent, VideoUtils.VIDEO_CODE_10000);
                    context.overridePendingTransition(R.anim.activity_up, R.anim.activity_down);
                }
                dissMiss();

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_order:
                orderVideo();
                break;
            case R.id.iv_delete_video:
                deleteVideo();
                break;
            case R.id.iv_add_video:
                AddVideo();
                break;
            case R.id.iv_recover: //撤销
                repealOperation();
                break;
            case R.id.iv_next://恢复
                recoverOperation();
                break;
            case R.id.iv_close:
                dissMiss();
                break;
        }
    }

    /**
     * 视屏排序
     */
    private void orderVideo() {
        if (VideoHelper.getIntence().getVideoPathList().size() <= 0) {
            CostarHintDialog costarHintDialog = new CostarHintDialog(context);
            costarHintDialog.setContentText("请先添加一个视频片段!");
            costarHintDialog.show();
            new android.os.Handler().postDelayed(() -> costarHintDialog.dissMiss(), 1500);
        } else {
            orderVideoDialog = new VideoOrderDialog(context, type);
            orderVideoDialog.show();
            VideoHelper.getIntence().getVideoSectionBeanList().get(currentPosition).setSelect(false);
            orderVideoDialog.refreshData();
        }
    }

    /**
     * 添加视频
     */
    private void AddVideo() {
        if (VideoHelper.getIntence().getVideoSectionBeanList().size()>0) {
            VideoHelper.getIntence().getVideoSectionBeanList().get(currentPosition).setSelect(false);
        }else {
            currentPosition = -1;
        }
        currentPosition++;
        VideoAddCommand videoAddCommand = new VideoAddCommand(currentPosition, 0, "");
        VideoHelper.getIntence().getCommendManger().pushCommandAndApply(videoAddCommand);
        viewPagerLayoutManager.scrollToPosition(currentPosition);
        refreshData();
        VideoHelper.getIntence().getVideoSectionBeanList().get(currentPosition).setSelect(true);
    }

    /**
     * 撤销操作
     */
    private void repealOperation() {
        Command undo = VideoHelper.getIntence().getCommendManger().undo();
        if (undo == null) {
            AppUtils.showHintDialogToast(context, "撤销失败!");
            return;
        }
        currentPosition = VideoHelper.getIntence().getOperationPosition(1, context, undo);
//                LogUtils.e(TAG, und0CommandName);
        refreshData();
    }

    /**
     * 恢复操作
     */
    private void recoverOperation() {
        Command redo = VideoHelper.getIntence().getCommendManger().redo();
        if (redo == null) {
            AppUtils.showHintDialogToast(context, "恢复失败!");
            return;
        }
        currentPosition = VideoHelper.getIntence().getOperationPosition(2, context, redo);
        refreshData();
    }

    /**
     * 删除视屏
     */
    private void deleteVideo() {
        if (currentPosition<0)return;
        VideoHelper.getIntence().getVideoSectionBeanList().get(currentPosition).setSelect(false);
        currentPosition = viewPagerLayoutManager.getCurrentPosition();
        ArrayList<String> videoPathList = VideoHelper.getIntence().getVideoPathList();
        if (videoPathList == null || videoPathList.size() == 0) return;
        if (videoPathList.size() > 0) {
            if (!TextUtils.isEmpty(VideoHelper.getIntence().getVideoPathByIndex(currentPosition))) {
                new ContentDialog(context).setContent("确定要删除该片段吗？").setCancelContent("取消").setAffirmContent("确定")
                        .setAffirmContentColor(R.color.red_bag_color).setOnTwoClickListener(new ContentDialog.OnTwoClickListener() {
                    @Override
                    public void onAffirm() {
                        VideoDeleteCommand videoDeleteCommand = new VideoDeleteCommand(currentPosition, VideoHelper.getIntence().getVideoTimeByIndex(currentPosition), VideoHelper.getIntence().getVideoPathByIndex(currentPosition));
                        VideoHelper.getIntence().getCommendManger().pushCommandAndApply(videoDeleteCommand);
                        if (currentPosition>0) {
                            currentPosition--;
                            viewPagerLayoutManager.scrollToPosition(currentPosition);
                        }else {
                            currentPosition--;
                        }
                        //刷新数据
                        refreshData();
                    }

                    @Override
                    public void onCancel() {

                    }
                }).show();
            } else {
                VideoDeleteCommand videoDeleteCommand = new VideoDeleteCommand(currentPosition, VideoHelper.getIntence().getVideoTimeByIndex(currentPosition), VideoHelper.getIntence().getVideoPathByIndex(currentPosition));
                VideoHelper.getIntence().getCommendManger().pushCommandAndApply(videoDeleteCommand);
                if (currentPosition>0) {
                    currentPosition--;

                }else {

                }
                //刷新数据
                viewPagerLayoutManager.scrollToPosition(currentPosition);
                refreshData();
            }
            mTvShootNum.setText("选择片段(" + VideoHelper.getIntence().getVideoPathList().size() + ")");
            if ( VideoHelper.getIntence().getVideoSectionBeanList().size()>0) {
                VideoHelper.getIntence().getVideoSectionBeanList().get(currentPosition).setSelect(true);
            }
        }
    }


    /**
     * 刷新数据
     */
    public void refreshData() {
        if (currentPosition == -1) {
            currentPosition = 0;
        }
        if (VideoHelper.getIntence().getVideoSectionBeanList().size()>0) {
            VideoHelper.getIntence().getVideoSectionBeanList().get(currentPosition).setSelect(true);
        }
        videoSliceSelectAdapter.setNewData(VideoHelper.getIntence().getVideoSectionBeanList());
        videoSliceTimeAdapter.setNewData(VideoHelper.getIntence().getVideoSectionBeanList());
        videoSliceTextAdapter.setNewData(VideoHelper.getIntence().getVideoSectionBeanList());

        if (VideoHelper.getIntence().getCommendManger().isCanRedo()) {
            mIvNext.setImageDrawable(context.getResources().getDrawable(R.drawable.next_step_black_icon));
            mIvNext.setEnabled(true);
        } else {
            mIvNext.setEnabled(false);
            mIvNext.setImageDrawable(context.getResources().getDrawable(R.drawable.next_step_black_icon_nopress));
        }

        if (VideoHelper.getIntence().getCommendManger().isCanUndo()) {
            mIvRecover.setImageDrawable(context.getResources().getDrawable(R.drawable.previous_black_icon));
            mIvRecover.setEnabled(true);
        } else {
            mIvRecover.setImageDrawable(context.getResources().getDrawable(R.drawable.previous_black_icon_nopress));
            mIvRecover.setEnabled(false);
        }
        if (VideoHelper.getIntence().getVideoPathList().size() >= 30 || VideoHelper.getIntence().getVideoListTime() / 1000 >= 60) {
            mIvAddVideo.setEnabled(false);
            mIvAddVideo.setImageDrawable(context.getResources().getDrawable(R.drawable.add_icon_press));
        } else {
            mIvAddVideo.setEnabled(true);
            mIvAddVideo.setImageDrawable(context.getResources().getDrawable(R.drawable.add_icon));
        }
        if (VideoHelper.getIntence().getVideoPathList().size() == 0) {
            //按钮置灰
            mIvDelVideo.setEnabled(false);
            mIvDelVideo.setImageDrawable(context.getResources().getDrawable(R.drawable.delete_icon_press));
        } else {
            mIvDelVideo.setEnabled(true);
            mIvDelVideo.setImageDrawable(context.getResources().getDrawable(R.drawable.delete_icon));
        }
        if (currentPosition!=-1) {
            viewPagerLayoutManager.scrollToPosition(currentPosition);
        }
        mTvShootNum.setText("选择片段  (" + VideoHelper.getIntence().getVideoInfoSize() + ")");
    }

    public interface OnDialogDissMissListener {
        void onDissMiss();
    }


    public void setOnDialogDissMissListener(OnDialogDissMissListener onDialogDissMissListener) {
        this.onDialogDissMissListener = onDialogDissMissListener;
    }

    public void show() {
        Window window = dialog.getWindow();
        window.setGravity(Gravity.CENTER);
        window.setLayout(AppUtils.getScreenWidthAndHeight(context)[0] - DesityUtils.dp2px(30), RecyclerView.LayoutParams.WRAP_CONTENT);
        dialog.show();
        videoSliceTimeAdapter.setWith(AppUtils.getScreenWidthAndHeight(context)[0] - DesityUtils.dp2px(55));
        videoSliceTextAdapter.setWith(AppUtils.getScreenWidthAndHeight(context)[0] - DesityUtils.dp2px(55));
        if (VideoHelper.getIntence().getViewPosition()!=-1) {
            currentPosition=VideoHelper.getIntence().getViewPosition();
        }else {
            if (VideoHelper.getIntence().getCurrentVideoPosition() != -1) {
                currentPosition = VideoHelper.getIntence().getCurrentVideoPosition();
            }
        }
        if (currentPosition == -1) {
            currentPosition = 0;
        }else {
            VideoHelper.getIntence().getVideoSectionBeanList().get(currentPosition).setSelect(false);
        }

    }

    public void dissMiss() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }
}
